package com.medvalley.tcm.weixin;

import com.alibaba.fastjson.JSONObject;
import com.medvalley.tcm.cache.GuavaCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Created by linsong on 2018/3/18.
 */
@Component
public class AccessToken extends WXResultHandler {

    private static Logger LOGGER = LoggerFactory.getLogger(AccessToken.class);

    private static String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    public static final String CACHE_KEY = "access_token";

    public synchronized String getAccessToken() throws WXException {
        String token = GuavaCache.getCacheValue(CACHE_KEY);
        if (StringUtils.isEmpty(token)) {
            token = refreshToken();
        }
        return token;
    }

    private String refreshToken() throws WXException {
        String appId = WXConfig.APP_ID;
        String appSecret = WXConfig.APP_SECRET;
        final Map<String, String> queryParas = ParaMap.create("appid", appId).put("secret", appSecret).getData();

        JSONObject result = retryDoWXRequest(url, queryParas, 3);

        String accessToken = result.getString("access_token");
        if (!StringUtils.isEmpty(accessToken)) {
            GuavaCache.putCache(CACHE_KEY, accessToken);
            return accessToken;
        }
        return null;
    }

    @Override
    JSONObject parseResult2Json(String responseString) {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" get AccessToken result {}", responseString);
        }
        JSONObject result = JSONObject.parseObject(responseString);
        String accessToken = result.getString("access_token");
        if (StringUtils.isEmpty(accessToken)) {
            LOGGER.warn(" get accessToken error,msg:{}", responseString);
            throw new RuntimeException(" get accessToken error");
        } else {
            return result;
        }
    }
}
